export enum DocUpdateStatusEnum {
  INIT = 'INIT', // 初始化,
  LOADED = 'LOADED', // "已加载",
  MODIFY = 'MODIFY', // "已修改，正在保存...",
  SAVED = 'SAVED' // "已保存"
}

export enum IframeToPlatformMsgType {
  TITLE_UPDATE = 'TITLE_UPDATE', // 更新标题
  STATUS_UPDATE = 'STATUS_UPDATE', // 状态标题
  KEY_DOWN_ESC = 'KEY_DOWN_ESC', // 按下ESC
}

/**
 * 状态通知器，监听文档更新状态和键盘ESC键按下事件，通知给iframe父页面
 */
export default function useStatusNotifier() {
  /**
   * 发送消息给平台
   * @param action   消息类型 IframeToPlatformMsgType
   * @param content  消息内容对象
   */
  const notifyPlatform = (action: string, content?:{}) => {
    window.parent.postMessage({action, content}, import.meta.env.VITE_BASE_URL)
  }

  const sendLoadedMsg = (date: Date) => {
    notifyPlatform(IframeToPlatformMsgType.STATUS_UPDATE, {status: DocUpdateStatusEnum.LOADED, date: date})
  }

  const sendSavingMsg = () => {
    notifyPlatform(IframeToPlatformMsgType.STATUS_UPDATE, {status: DocUpdateStatusEnum.MODIFY, date: null})
  }

  const sendSavedMsg = (date: Date) => {
    notifyPlatform(IframeToPlatformMsgType.STATUS_UPDATE, {status: DocUpdateStatusEnum.SAVED, date: date})
  }

  const ESClistener = (event: KeyboardEvent) => {
    if ((event.ctrlKey || event.metaKey) && event.key === 's') {
      event.preventDefault()
    }
    else if (event.code === 'Escape') {
      notifyPlatform(IframeToPlatformMsgType.KEY_DOWN_ESC)
    }
  }

  return {sendLoadedMsg, sendSavingMsg, sendSavedMsg, ESClistener}
}